<?php

namespace app\admin\controller\Shop;

use addons\wechat\library\Config as ConfigService;
use app\admin\model\Shop;
use app\admin\model\Shopuser;
use app\admin\model\User;
use app\admin\model\Useramount;
use app\admin\model\Usermsgweixin;
use app\admin\model\Worktype;
use app\common\controller\Backend;
use EasyWeChat\Factory;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Shopjobuser extends Backend
{
    
    /**
     * Shopjobuser模型对象
     * @var \app\admin\model\Shopjobuser
     */
    protected $model = null;
    protected $wxapp = null;


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Shopjobuser;
        $this->wxapp = Factory::officialAccount(ConfigService::load());

    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model->with(['user','shop'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                if($v['status'] == -1){
                    $list[$k]['status'] = "待处理";
                }else if($v['status'] == 1){
                    $list[$k]['status'] = "我想要";
                }else if($v['status'] == 0){
                    $list[$k]['status'] = "不想要";
                }else if($v['status'] == 2){
                    $list[$k]['status'] = "处理完成";
                }else if($v['status'] == 3){
                    $list[$k]['status'] = "已入职";
                }
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);

        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");

            if($params['status'] == 3 && $row['status'] != 3){

                $shopUserModel = new Shopuser();
                $shopUserModel->where('uid',$row['uid'])->update(['status'=>-2]);//把之前的关系废除

                error_log("=====row====".json_encode($row));
                $id =  $shopUserModel->insertGetId(['uid'=>$row['uid'],'shopId'=>$row['shopid'],'workid'=>$row['workid'],
                    'createtime'=>time(),'status'=>1]);
               if($id>0){

                   $userModel = new User();
                   $userModel->where('id',$row['uid'])->update(["job_status"=>1]);

                   //奖励100推荐奖励 奖励100积分
                   $userModel =new User();
                   $user = $userModel->where('id',$row['uid'])->find();
                   $ref_user = $userModel->where('id',$user['ref_uid'])->find();
                   $userAmountModel = new Useramount();
                   $userAmountModel->insert(['uid'=>$ref_user['id'],'amount'=>100,'createtime'=>time(),'type'=>1,'desc'=>$user['username']."入职推荐奖励"]);

                   $usermsgModel = new Usermsgweixin();
                   $refWx  = $usermsgModel->where('user_id',$user['ref_uid'])->find();
                   if($refWx){
                       $t = $this->wxapp->template_message->send([
                           'touser' => $refWx['openid'],
                           'template_id' => 'UGjp5CSKqnH4h1rjErKPKu57VG6DSJE2wz5hbNH5U5c',
                           'data' => [
                               'first' => "恭喜您，一笔佣金结算成功",
                               'keyword1' => "佣金来自 ".$user['username'],
                               'keyword2' => "推荐技师入职奖励",
                               'keyword3' => "推荐入职奖励",
                               'keyword4' =>  "推荐奖励",
                               'keyword5' =>  100,
                               'remark' => '更多结算信息，请查看账户余额明细',
                           ],
                       ]);

                   }
               }

            }else{
                $this->error(__('不需要再做入职操作'));

            }
        }
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $userModel = new User();
        $user = $userModel->where('id',$row['uid'])->find();

        $shopModel = new Shop();
        $shop = $shopModel->where('id',$row['shopid'])->find();



        $this->assign("user",$user);
        $this->assign("shop",$shop);

        return parent::edit($ids);
    }
    

}
